import cv2
import pyautogui
import win32con
import win32gui
from PyQt5.QtCore import QThread
from pyperclip import copy

from config import Common
from core.engine import engine
from core.log import log
from core.ocr_engine import ocr_engine
from res.url import Scene, ResUrl
from static import config
from util import reg_template
import xlrd
from os import path
import os
from shutil import copyfile


class BrushMitamaThread(QThread):
    def __init__(self):
        super(BrushMitamaThread, self).__init__()
        self.is_running = True

    def stop(self):
        self.is_running = False

    def input_text(self, x, y, text):
        pyautogui.moveTo(x, y, duration=config.SHIFT_TIME)
        pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.press('backspace')
        copy(text)
        pyautogui.hotkey('ctrl', 'v')
        log.print("输入文字：" + text)
        self.msleep(config.ACTION_INTERVAL_TIME)

    def move_click(self, x, y):
        pyautogui.moveTo(x, y, duration=config.SHIFT_TIME)
        pyautogui.click()
        self.msleep(config.ACTION_INTERVAL_TIME)

    def click_search(self):
        pyautogui.moveTo(700, 160, duration=config.SHIFT_TIME)
        pyautogui.click()
        log.print("单击搜索按钮")
        self.msleep(config.ACTION_INTERVAL_TIME * 2)

    def click_upload(self):
        pyautogui.moveTo(1100, 220, duration=config.SHIFT_TIME)
        pyautogui.click()
        log.print("单击上传按钮")
        self.msleep(config.ACTION_INTERVAL_TIME)

    def click_table_row(self, screen_capture, header_left, header_right, header_bottom, line_height, row):
        top = header_bottom + row * line_height
        bottom = header_bottom + (row + 1) * line_height
        left = header_left
        right = header_right
        cv2.imwrite(ResUrl.CUR_LINE_PATH,
                    screen_capture[top:bottom,
                    left:right])
        x = (left + right) / 2
        y = (top + bottom) / 2
        self.move_click(x, y)

    def get_col(self, template_path, screen_capture, line_height):
        template = cv2.imread(template_path, 0)
        find_flag, left_top, right_bottom = reg_template(screen_capture, template)
        bottom = right_bottom[1]
        left = left_top[0]
        right = right_bottom[0]
        res = []
        for row_i in range(7):
            line_top = bottom + row_i * line_height
            line_bottom = bottom + (row_i + 1) * line_height
            cur_line = screen_capture[line_top:line_bottom, left:right]
            txt = ocr_engine.do(cur_line)
            self.msleep(100)
            res.append(txt)
        return res

    def get_target_row(self, identifier, capability_category, screen_capture, line_height):
        factory_numbers = self.get_col(ResUrl.FACTORY_NUMBER_PATH, screen_capture, line_height)
        capability_categories = self.get_col(ResUrl.CAPABILITY_CATEGORY_PATH, screen_capture, line_height)
        print(factory_numbers)
        print(capability_categories)
        for i in range(len(factory_numbers)):
            x1 = factory_numbers[i]
            x2 = capability_categories[i]
            if x1 == str(identifier) and x2 == str(capability_category):
                return i
        return None

    def click_item(self, identifier, capability_category):
        video_info = engine.video_info
        screen_capture = video_info[Common.KEY_SCREEN_CAPTURE]
        find_item_flag = False
        # 截取表格
        template = cv2.imread(ResUrl.TABLE_HEADER_PATH, 0)
        find_header_flag, header_left_top, header_right_bottom = reg_template(screen_capture, template)
        if find_header_flag:
            log.print("找到表格Title，开始识别表格，需要等待一段时间")
            line_height = 25
            target_row = self.get_target_row(identifier, capability_category, screen_capture, line_height)
            if target_row is not None:
                self.click_table_row(screen_capture,
                                     header_left_top[0],
                                     header_right_bottom[0],
                                     header_right_bottom[1],
                                     line_height,
                                     target_row)
                find_item_flag = True
            else:
                log.print("未找到目标行")
        else:
            log.print("未找到表格Title")
            self.msleep(config.ACTION_INTERVAL_TIME)
        return find_item_flag

    def choose_file(self, simulator_handle, pdf_path):
        # 输入文件名
        combo_box_ex32 = win32gui.FindWindowEx(simulator_handle, 0, "ComboBoxEx32", None)
        combo_box = win32gui.FindWindowEx(combo_box_ex32, 0, "ComboBox", None)
        file_name_edit = win32gui.FindWindowEx(combo_box, 0, "Edit", None)
        win32gui.SendMessage(file_name_edit, win32con.WM_SETTEXT, None, pdf_path)
        self.msleep(config.ACTION_INTERVAL_TIME)
        # 点击取消
        confirm = win32gui.FindWindowEx(simulator_handle, 0, 'Button', None)
        win32gui.SendMessage(confirm, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, 0)
        win32gui.SendMessage(confirm, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0)
        log.print("点击确认")

    def get_alnum_index(self, text):
        text = str(text)
        max_alnum_len = 0
        start = 0
        end = 0
        for i in range(len(text)):
            for j in range(i, len(text)):
                new_text = text[i:j + 1]
                if new_text.encode('utf-8').isalnum():
                    if start == 0:
                        start = i
                    if len(new_text) > max_alnum_len:
                        end = j
        return start, end + 1

    def get_all_file(self):
        root_path = ResUrl.PDF_PATH
        files = []
        for filename in os.listdir(root_path):
            filename_no_suffix = path.splitext(filename)[0]
            company = filename_no_suffix.split("_")[0]
            text2 = filename_no_suffix.split("_")[1]
            start_alnum_index, end_alnum_index = self.get_alnum_index(text2)
            appliances = text2[:start_alnum_index]
            identifier = text2[start_alnum_index:end_alnum_index]
            capability_category = text2[end_alnum_index:]
            files.append({"path": path.join(root_path, filename),
                          "company": company,
                          "appliances": appliances,
                          "identifier": identifier,
                          "capability_category": capability_category,
                          "filename": filename})
        return files

    def run(self):  # 线程执行函数
        log.print("开始执行脚本")
        files = self.get_all_file()
        self.msleep(config.ACTION_INTERVAL_TIME)
        for file in files:
            log.print("开启新循环")
            reg_info = engine.reg_info
            video_info = engine.video_info
            scene = reg_info[Common.KEY_REG_SCENE]
            simulator_handle = video_info[Common.KEY_SIMULATOR_HANDLE]
            while scene != Scene.RECORD:
                reg_info = engine.reg_info
                video_info = engine.video_info
                simulator_handle = video_info[Common.KEY_SIMULATOR_HANDLE]
                scene = reg_info[Common.KEY_REG_SCENE]
                self.msleep(1000)
            log.print("进入主页")
            pdf_path = file["path"]
            company = file["company"]
            appliances = file["appliances"]
            identifier = file["identifier"]
            filename = file["filename"]
            capability_category = file["capability_category"]
            log.print("identifier:" + str(identifier) + ", capability_category:" + str(capability_category))
            log.print("文件名:" + str(filename))
            self.input_text(200, 160, company)
            self.input_text(200, 180, appliances)
            self.click_search()
            find_item_flag = self.click_item(identifier, capability_category)
            if find_item_flag:
                self.click_upload()
                while scene != Scene.CHOOSE:
                    reg_info = engine.reg_info
                    video_info = engine.video_info
                    simulator_handle = video_info[Common.KEY_SIMULATOR_HANDLE]
                    scene = reg_info[Common.KEY_REG_SCENE]
                    self.msleep(1000)
                log.print("进入选择文件页面")
                self.choose_file(simulator_handle, pdf_path)
                # 成功之后拷贝文件
                log.print("拷贝文件至success")
                copyfile(pdf_path, path.join(ResUrl.SUCCESS_PATH, filename))
            else:
                # 失败之后拷贝文件
                log.print("拷贝文件至fail")
                copyfile(pdf_path, path.join(ResUrl.FAIL_PATH, filename))
        log.print("全部执行完毕")
